package cn.lu.train.util;

import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;

import java.io.File;

import cn.lu.train.App;
import cn.lu.train.downloader.SimpleTarget;
import cn.lu.train.downloader.Downloader;

public class ImageUtils {
    private static final String SAVE_IMAGE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();

    public static void saveImage(String imgUrl, final String savePathDir, final String filename) {
        Downloader.gen()
                .build()
                .create(imgUrl)
                .setPath(savePathDir + "/" + filename)
                .setDownloadListener(new SimpleTarget() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.show("图片保存失败");
                    }

                    @Override
                    public void onComplete(String path) {
                        Toast.show("图片保存成功");
                        scannerNewImageFile(new File(path));
                    }
                }).start();
    }

    /**
     * 将下载的图片文件保存在本地
     */
    public static void saveImageToDisk(File cacheFile, File destFile) {
        saveImageToDisk(cacheFile, destFile, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {

            }
        }, true);
    }

    /**
     * 将下载的图片文件保存在本地
     */
    public static void saveImageToDisk(File cacheFile, File destFile, MediaScannerConnection.OnScanCompletedListener listener) {
        saveImageToDisk(cacheFile, destFile, listener, true);
    }

    /**
     * 将下载的图片文件保存在本地
     */
    public static void saveImageToDisk(File cacheFile, File destFile, MediaScannerConnection.OnScanCompletedListener listener, boolean toGallery) {
        if (FileUtils.nioCopyFile(cacheFile, destFile)) {
            if (toGallery) {
                scannerNewImageFile(destFile, listener);
            }
        }

    }

    public static void scannerNewImageFile(File file) {
        scannerNewImageFile(new String[]{file.getAbsolutePath()}, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String path, Uri uri) {

            }
        });
    }

    public static void scannerNewImageFile(File file, MediaScannerConnection.OnScanCompletedListener listener) {
        scannerNewImageFile(new String[]{file.getAbsolutePath()}, listener);
    }

    public static void scannerNewImageFile(String[] filePaths, MediaScannerConnection.OnScanCompletedListener listener) {
        startScanner(filePaths, new String[]{"image/jpeg"}, listener);
    }

    private static void startScanner(String[] filePaths, String[] mimeTypes, MediaScannerConnection.OnScanCompletedListener listener) {
        MediaScannerConnection.scanFile(App.get(), filePaths, mimeTypes, listener);
    }
}
